package com.atguigu.crowd.handler;

import com.atguigu.crowd.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class RedisHandler {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/set/Redis/Key/Value/Remote")
    ResultEntity<String> setRedisKeyValueRemote(
            @RequestParam("key") String key,
            @RequestParam("value") String value){

        try {
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();

            operations.set(key,value);

            return ResultEntity.successData();
        } catch (Exception e) {
            e.printStackTrace();

            return ResultEntity.errorData(e.getMessage());
        }


    }

    //设置带超时时间的
    @RequestMapping("/set/Redis/Key/Value/Remote/With/Timeout")
    ResultEntity<String> setRedisKeyValueRemoteWithTimeout(
            @RequestParam("key") String key,
            @RequestParam("value") String value,
            @RequestParam("time")long time,
            @RequestParam("timeUnit") TimeUnit timeUnit){

        try {
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();

            operations.set(key,value,time,timeUnit);

            return ResultEntity.successData();
        } catch (Exception e) {
            e.printStackTrace();

            return ResultEntity.errorData(e.getMessage());
        }
    }

    @RequestMapping("/get/Redis/String/Value/By/Key")
    ResultEntity<String> getRedisStringValueByKey(@RequestParam("key") String key){
        try {
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();

            String value = operations.get(key);

            return ResultEntity.successResuleData(value);
        } catch (Exception e) {
            e.printStackTrace();

            return ResultEntity.errorData(e.getMessage());
        }
        
    }


    @RequestMapping("/remove/Redis/Key/Remote")
    ResultEntity<String> removeRedisKeyRemote(@RequestParam("key") String key){
        try {

            stringRedisTemplate.delete(key);

            return ResultEntity.successData();
        } catch (Exception e) {
            e.printStackTrace();

            return ResultEntity.errorData(e.getMessage());
        }
    }
}
